
class GimytvSearch extends AbstractPlugin {

  static BASE_URL = 'https://gimytv.io';

  async fetchSearchResults(query) {
    const searchUrl = `${GimytvSearch.BASE_URL}/search?q=${encodeURIComponent(query)}`;
    const http_headers = {
      'User-Agent': GimytvSearch.DEFAULT_USER_AGENT,
      'Origin': GimytvSearch.BASE_URL,
    };
    const result  = await doHttpRequestSync(searchUrl, { headers: http_headers });
    if(result.status !== 'success') {
      return null;
    }
    const data = result.body;

    const parser = new DOMParser();
    const doc = parser.parseFromString(data, 'text/html');

    const searchResults = [];

    const results = doc.querySelectorAll('.details-info-min');
    results.forEach(result => {
      const searchResult = new SearchResult();
      searchResult.site_icon = '/plugins/gimytv/icon.png';
      searchResult.site_name = GimytvSearch.BASE_URL.replace(/https?:\/\/(www\.)?/, '');

      const imageElement = result.querySelector('.video-pic');
      const imageUrl = imageElement ? imageElement.getAttribute("data-original").trim() : '';
      searchResult.image = imageUrl.startsWith('/') ? `${GimytvSearch.BASE_URL}${imageUrl}` : imageUrl;
      const titleElement = result.querySelector('.details-info a');
      searchResult.title = titleElement.getAttribute('title');
      const href = titleElement.getAttribute('href');
      searchResult.link = href.startsWith('/') ? `${GimytvSearch.BASE_URL}${href}` : href;

      const infoElements = result.querySelectorAll('.details-info.info li');
      const filteredElements = Array.from(infoElements).filter(li => !li.querySelector('a'));
      const infos = [];
      filteredElements.forEach(infoElement => {
        const info = infoElement.textContent.trim();
        if(info) {
          infos.push(info);
        }
      })
      searchResult.description = infos.join('\n');

      searchResults.push(searchResult);
    });
    return searchResults;
  }

}
Registry.registerClass("GimytvSearch", new GimytvSearch());